﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AntikCompta.Data;

namespace AntikCompta
{
    public partial class CaisseWnd : Form
    {
        private Exercice mExercice;
        private Stock mStock;
        private DataMng mDataMng;
        internal CaisseWnd(ref DataMng aDataMng, ref Stock aStock, ref Exercice aExercice)
        {
            mExercice = aExercice;
            mStock = aStock;
            mDataMng = aDataMng;
            InitializeComponent();
            treeView1.SelectedNode = treeView1.Nodes[DateTime.Now.Month - 1];

            Text += " " + mExercice.Annee;

            mExercice.DataChanged += new DataChangedHandler(mExercice_DataChanged);
            CouleurLotMng.GetObject().ColorChanged += new DataChangedHandler(CaisseWnd_ColorChanged);
        }

        void CaisseWnd_ColorChanged()
        {
            RefreshView();
        }

        void mExercice_DataChanged()
        {
            RefreshView();
        }

        private int CurrentMois
        {
            get{
                if (treeView1.SelectedNode == null)
                    return -1;

                return Convert.ToInt32(treeView1.SelectedNode.Tag);
            }
        }

        private void RefreshView()
        {
            datas.Rows.Clear();
            int mois = CurrentMois;

            if (mois < 0)
                return;

            float recettes = AddRestePrecedant(mois);
            recettes += AddVentes(mois);
            recettes += AddRecette(mois);

            float depenses = AddAchats(mois);
            depenses += AddFrais(mois);
            depenses += AddDepense(mois);
            
            datas.Sort(datas.Columns[0], ListSortDirection.Ascending);

            AfficheReste();

            lbl_out.Text = "Total des dépenses: " + Math.Round(depenses, 2) + " €, total des recettes: " + Math.Round(recettes, 2) + " €";
            lbl_out.Text += " reste: " + Math.Round(recettes - depenses,2) + " €";
        }

        private void AfficheReste()
        {
            float value = 0;
            foreach (DataGridViewRow row in datas.Rows)
            {
                if(row.Cells[3].Value!=null)
                    value += Convert.ToSingle(row.Cells[3].Value);
                else if(row.Cells[4].Value!=null)
                    value -= Convert.ToSingle(row.Cells[4].Value);
             
                row.Cells[5].Value = Math.Round(value,2);

                if( value<0 )
                    row.DefaultCellStyle.BackColor = Color.Red;
            }
        }

        private float GetRestePrecedant(int aMois)
        {
            DateTime date = new DateTime(mExercice.Annee, aMois, 1);
            return (float)Math.Round(mDataMng.GetResteCaisse(ref mStock, date.AddDays(-1)), 2);
        }

        private float AddRestePrecedant(int aMois)
        {
            DateTime date = new DateTime(mExercice.Annee, aMois, 1);
            int idx = datas.Rows.Add();
            datas.Rows[idx].Cells[0].Value = date;

            float somme = GetRestePrecedant(aMois);
            
            datas.Rows[idx].Cells[2].Value = "Reste du mois précédant";
            if( somme>= 0 )
                datas.Rows[idx].Cells[3].Value = somme;
            else
                datas.Rows[idx].Cells[4].Value = Math.Abs(somme);

            datas.Rows[idx].Cells[6].Value = -1;

            return somme;
        }

        private float AddDepense(int mois)
        {
            float somme = 0;
            foreach (CaisseElement elmt in mExercice.Caisse.Depences)
            {
                if (elmt.Date.Month == mois)
                {
                    int idx = datas.Rows.Add();
                    datas.Rows[idx].Cells[0].Value = elmt.Date;
                    datas.Rows[idx].Cells[2].Value = elmt.Description;
                    datas.Rows[idx].Cells[4].Value = elmt.Somme;
                    datas.Rows[idx].Cells[6].Value = elmt.Reference;

                    somme += elmt.Somme;
                }
            }

            return somme;
        }

        private float AddRecette(int mois)
        {
            float somme = 0;
            foreach (CaisseElement elmt in mExercice.Caisse.Recettes)
            {
                if (elmt.Date.Month == mois)
                {
                    int idx = datas.Rows.Add();
                    datas.Rows[idx].Cells[0].Value = elmt.Date;
                    datas.Rows[idx].Cells[2].Value = elmt.Description;
                    datas.Rows[idx].Cells[3].Value = elmt.Somme;
                    datas.Rows[idx].Cells[6].Value = elmt.Reference;

                    somme += elmt.Somme;
                }
            }
            return somme;
        }

        private float AddFrais(int aMois)
        {
            float somme = 0;
            foreach (CaisseElement ce in mExercice.Frais)
            {
                if (ce.Date.Month == aMois)
                    somme += ce.Somme;
            }

            int idx = datas.Rows.Add();
            datas.Rows[idx].Cells[0].Value = new DateTime(mExercice.Annee, aMois, DateTime.DaysInMonth(mExercice.Annee, aMois));
            datas.Rows[idx].Cells[2].Value = "Frais du mois de " + treeView1.SelectedNode.Text;
            datas.Rows[idx].Cells[4].Value = Math.Round(somme, 2);
            datas.Rows[idx].Cells[6].Value = -1;

            return somme;
        }

        private float AddVentes(int aMois)
        {
            float somme = 0;
            List<Produit> liste;
            if (mStock.GetVentes(mExercice.Annee, out liste) == true)
            {
                foreach (Produit p in liste)
                {
                    Especes esp = p.ModePayementVente as Especes;
                    if ((esp != null) && (p.DateVente.Month == aMois))
                    {
                        int idx = datas.Rows.Add();
                        datas.Rows[idx].Cells[0].Value = p.DateVente;
                        datas.Rows[idx].Cells[1].Value = p.Reference;
                        datas.Rows[idx].Cells[2].Value = p.Nom;
                        datas.Rows[idx].Cells[3].Value = p.PrixVente;
                        datas.Rows[idx].Cells[6].Value = -1;

                        Color couleur;
                        if (CouleurLotMng.GetObject().GetColor(Produit.GetLotRef(p.Reference), out couleur))
                            datas.Rows[idx].DefaultCellStyle.BackColor = couleur;

                        somme += p.PrixVente;
                    }
                }
            }
            return somme;
        }

        private float AddAchats(int aMois)
        {
            float somme = 0;
            foreach (Produit p in mExercice.ProduitListe)
            {
                Especes esp = p.ModePayementAchat as Especes;
                if ((esp != null) && (p.DateAchat.Month == aMois) )
                {
                    int idx = datas.Rows.Add();
                    datas.Rows[idx].Cells[0].Value = p.DateAchat;
                    datas.Rows[idx].Cells[1].Value = p.Reference;
                    datas.Rows[idx].Cells[2].Value = p.Nom;
                    datas.Rows[idx].Cells[4].Value = p.PrixAchat;
                    datas.Rows[idx].Cells[6].Value = -1;

                    Color couleur;
                    if (CouleurLotMng.GetObject().GetColor(Produit.GetLotRef(p.Reference), out couleur))
                        datas.Rows[idx].DefaultCellStyle.BackColor = couleur;

                    somme += p.PrixAchat;
                }
            }
            return somme;
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            RefreshView();
        }

        private void bt_fermer_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void bt_ajt_Click(object sender, EventArgs e)
        {
            int mois = CurrentMois;
            if (mois < 0)
                return;

            NewCaisseWnd wnd = new NewCaisseWnd(ref mExercice, mois);
            wnd.ShowDialog();
        }

        private void bt_suppr_Click(object sender, EventArgs e)
        {
            if( (datas.SelectedRows==null) || (datas.SelectedRows.Count<=0))
                    return;

            int reference = Convert.ToInt32(datas.SelectedRows[0].Cells[6].Value);
            if (reference == -1)
                return;

            if (MessageBox.Show("Etes vous certain de vouloir supprimer: " + datas.SelectedRows[0].Cells[2].Value.ToString() + "?", "Attention", MessageBoxButtons.OKCancel) != DialogResult.OK)
                return;

            mExercice.SupprimerCaisse(reference);
        }

        private void datas_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int reference = Convert.ToInt32(datas.Rows[e.RowIndex].Cells[6].Value);
            if (reference == -1)
                return;

            NewCaisseWnd wnd = new NewCaisseWnd(ref mExercice, reference);
            wnd.ShowDialog();
        }

        private void CaisseWnd_FormClosing(object sender, FormClosingEventArgs e)
        {
            mExercice.DataChanged -= new DataChangedHandler(mExercice_DataChanged);
            CouleurLotMng.GetObject().ColorChanged -= new DataChangedHandler(CaisseWnd_ColorChanged);
        }

        private void datas_SelectionChanged(object sender, EventArgs e)
        {
            txt_status.Text = "";
            if ((datas.SelectedRows == null) || (datas.SelectedRows.Count <= 0))
                return;

            float valeurdep = 0;
            float valeurrec = 0;
            foreach (DataGridViewRow row in datas.SelectedRows)
            {
                if( row.Cells[3].Value != null )
                    valeurrec += (float)row.Cells[3].Value;
                else if (row.Cells[4].Value != null)
                    valeurdep += (float)row.Cells[4].Value;
            }
            if (valeurdep > 0)
                txt_status.Text = "somme des dépences = " + Math.Round(valeurdep, 2) + " €";

            if (valeurrec > 0)
                txt_status.Text +=" somme des recettes = " + Math.Round(valeurrec, 2) + " €";
        }

        private void bt_imprimer_Click(object sender, EventArgs e)
        {
            DataGridView dgp = Tools.Copy_DataGridView(datas);

            Tools.AddTotaux(dgp, 3, 4);
            
            PrintDGV.Print_DataGridView(dgp, "Livre de caisse du mois " + treeView1.SelectedNode.Text + " " + mExercice.Annee);
        }

    }
}
